package it.davial.mgwt.server;

import static it.softphone.commons.util.LogUtil.logger; 
import static it.davial.mgwt.server.Utility.ManagmentId;
import static  it.davial.mgwt.server.Sql.Visit.*;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;



import it.davial.mgwt.client.Visit;


public class VisitUtils {

	
	/**
	 * find all visit without criteria
	 * @return List<Visit>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Visit> findAllVisit()throws Exception{
		
		EntityManager newEm=null;
		List<Visit> result=new ArrayList<Visit>();
		Utility.Logs.startFunction("VisitUtils", "findAllVisit", new String[]{});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			logger.info(" Visit(s) found:".concat(String.valueOf(result.size()))  );
			
			result =(List<Visit>)newEm.createNativeQuery(SELECT_ALL,Visit.class).getResultList();
	
			logger.info(" Visit(s) found:".concat(String.valueOf(result.size()))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("VisitUtils:findAllVisit",e);
		}catch(Exception e){
			logger.error("VisitUtils:findAllVisit",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}
	
	/**
	 * find all visit without criteria
	 * @return List<Visit>
	 * @throws Exception
	 */
	public static Visit findVisitById(String id)throws Exception{
		
		EntityManager newEm=null;
		Visit result=null;
		id=Utility.StringUtils.nullUtility(id);
		Utility.Logs.startFunction("VisitUtils", "findVisitById", new String[]{id});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			
			result =(Visit)newEm.createNativeQuery(SELECT_BY_ID,Visit.class).
										setParameter(1,id ).getSingleResult();
	
			logger.info(" Visit found:".concat(String.valueOf(result))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("VisitUtils:findVisitById",e);
		}catch(Exception e){
			logger.error("VisitUtils:findVisitById",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}

	/**
	 * find all visit without criteria
	 * @return List<Visit>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Visit> findVisitByIdPersonAndDate(String surname,String date)throws Exception{
		
		EntityManager newEm=null;
		List<Visit> result=null;
		
		surname=Utility.StringUtils.nullUtility(surname);
		date=Utility.StringUtils.nullUtility(date);
		
		Utility.Logs.startFunction("VisitUtils", "findVisitByIdPersonAndDate", 
												new String[]{surname,date});
		
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			
			
			result =(List<Visit>)newEm.createNativeQuery(SELECT_BY_IDPERSON_DATE,Visit.class).
										setParameter(1,surname ).
										setParameter(2,surname ).
										setParameter(3,date ).
										setParameter(4,date ).
										getResultList();
	
			logger.info(" Visit(s) found:".concat(String.valueOf(result.size()))  );
			
		}catch(javax.persistence.NoResultException e){
			logger.warn("VisitUtils:findVisitByIdPersonAndDate",e);
		}catch(Exception e){
			logger.error("VisitUtils:findVisitByIdPersonAndDate",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return result;
	}

	/**
	 * create a visit
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean createVisit(Visit visit)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("VisitUtils", "createVisit", new String[]{visit.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    visit.setIdVisit(ManagmentId.getNextId(IdEntity.VISIT));
		    visit.setDataInsert(Utility.Date.nowDateDb());
		    visit.setDataUpdate(Utility.Date.nowDateDb());
			newEm.persist(visit);
			logger.info("visit created..." );
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("VisitUtils:createVisit",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	/**
	 * merge a visit
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean mergeVisit(Visit visit)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("VisitUtils", "merge", new String[]{visit.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    visit.setDataUpdate(Utility.Date.nowDateDb());
		    visit.setDataInsert(Utility.Date.webFormatToDateDb(visit.getDataInsert()));

			newEm.merge(visit);
			logger.info("visit mergeed..." );
			 tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("VisitUtils:mergeVisit",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	/**
	 * delete a visit
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean deleteVisit(Visit visit)throws Exception{
		EntityManager newEm=null;
		EntityTransaction tx =null;
		Utility.Logs.startFunction("VisitUtils", "delete", new String[]{visit.toString()});
		try{
			EntityManagerFactory emf=JpaUtility.getEntityFactory();
			if (emf==null){
				logger.warn("EntityManagerFactory is null...");
				throw new Exception();
			}
			newEm =emf.createEntityManager();
			tx = newEm.getTransaction();
		    tx.begin();
		    visit.setState(Utility.Costants.DISABLED);
			logger.info(String.format("visit delete...[%s]",visit) );
			visit.setDataUpdate(Utility.Date.nowDateDb());
		    visit.setDataInsert(Utility.Date.webFormatToDateDb(visit.getDataInsert()));

			newEm.merge(visit);
			
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			logger.error("VisitUtils:deleteVisit",e);
			throw e;
		}finally{
			if (newEm!=null)newEm.close();
		}
		return true;
	}
	
	
}
